/*******************************************************************************
 * Package: com.song.boot.springstudy.thread.threadLocal
 * Type:    MyThreadLocal
 * Date:    2022-05-29 12:50
 *
 * 
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.boot.springstudy.thread.threadLocal;

import com.song.boot.springstudy.entity.UserEntity;


/**
 * 功能描述：ThreadLocal案例
 *
 * @author Songxianyang
 * @date 2022-05-29 12:50
 */

public class MyThreadLocal {
    public static void main(String[] args) {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(1);
        userEntity.setName("songXY");
        userEntity.setType("VIP");
        new Service1().M(userEntity);
        System.out.println("以下是上来就直接初始化对象");
        new InitialValueService4().M();
    }
}

class Service1 {
    public void M(UserEntity entity) {
        ThreadLocalUser.userEntityThreadLocal.set(entity);
        System.out.println("通过set的方式往ThreadLocal放对象");
        System.out.println("---------------");
        new Service2().M();
        System.out.println("---------------");
        new Service3().M();
    }
}

class Service2 {
    public void M() {
        UserEntity userEntity = ThreadLocalUser.userEntityThreadLocal.get();
        System.out.println(userEntity.getId());
        System.out.println(userEntity.getName());
        System.out.println(userEntity.getType());
        
    }
}

class Service3 {
    public void M() {
        UserEntity userEntity = ThreadLocalUser.userEntityThreadLocal.get();
        System.out.println(userEntity.getId());
        System.out.println(userEntity.getName());
        System.out.println(userEntity.getType());
        // 用完之后记得 remove 掉防止OOM
        ThreadLocalUser.userEntityThreadLocal.remove();
    }
}

class ThreadLocalUser {
    public static ThreadLocal<UserEntity> userEntityThreadLocal = new ThreadLocal<>();
}

class InitialValue {
    public static ThreadLocal<UserEntity> userEntityThreadLocal =  ThreadLocal.withInitial(()->{
        UserEntity userEntity = new UserEntity();
        userEntity.setId(2);
        userEntity.setName("喜羊羊");
        userEntity.setType("SVIP");
        return userEntity;
    });
}

class InitialValueService4 {
    public void M() {
        UserEntity userEntity = InitialValue.userEntityThreadLocal.get();
        System.out.println(userEntity.getId());
        System.out.println(userEntity.getName());
        System.out.println(userEntity.getType());
        System.out.println("---------------");
        new InitialValueService5().M();
    }
}
class InitialValueService5 {
    public void M() {
        UserEntity userEntity = InitialValue.userEntityThreadLocal.get();
        System.out.println(userEntity.getId());
        System.out.println(userEntity.getName());
        System.out.println(userEntity.getType());
        
    }
}